﻿using AntMovement.Core;
using AntMovement.Core.Entity;
using AntMovement.Core.Hardware;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AntMovement.SDK.LTSMC
{
    public class Motion : IMotionBase
    {
        private int _index;
        public int Index => _index;
        private string _name;

        public string Name => _name;
        private long _status = -1;
        private List<Axis> _axes;

        public Motion(string name, int index, List<Axis> axes)
        {
            _name = name;
            _index = index;
            _axes = axes;
        }

        public string Close()
        {
            LTSMC.smc_board_close((ushort)_index);
            _status = -1;
            return "ok";
        }

        public long GetStatus() => _status;

        public string Open()
        {
            short iret = LTSMC.smc_board_init((ushort)_index, 2, _name, 0);
            if (iret == 0)
            {
                foreach (var item in _axes)
                {
                    iret = LTSMC.smc_write_sevon_pin(item.CardNo, item.AxisID, 0);//打开伺服使能
                    if (iret != 0)
                    {
                        return $"smc_write_sevon_pin：{iret}";
                    }
                    iret = LTSMC.smc_set_alm_mode(item.CardNo, item.AxisID, 0, 0, 0);//设置报警使能，关闭报警
                    if (iret != 0)
                    {
                        return $"smc_set_alm_mode：{iret}";
                    }
                    iret = LTSMC.smc_set_pulse_outmode(item.CardNo, item.AxisID, 0);//设置脉冲模式
                    if (iret != 0)
                    {
                        return $"smc_set_pulse_outmode：{iret}";
                    }
                    double equiv = item.UnitConversion.CyclePulse / item.UnitConversion.WeeklyItinerary;
                    iret = LTSMC.smc_set_equiv(item.CardNo, item.AxisID, 1);//设置脉冲当量
                    if (iret != 0)
                    {
                        return $"smc_set_equiv：{iret}";
                    }
                    iret = LTSMC.smc_set_home_pin_logic(item.CardNo, item.AxisID, 0, 0);
                    if (iret != 0)
                    {
                        return $"smc_set_home_pin_logic：{iret}";
                    }
                    iret = LTSMC.smc_set_el_mode(item.CardNo, item.AxisID, 1, 0, 0);
                    if (iret != 0)
                    {
                        return $"smc_set_home_pin_logic：{iret}";
                    }
                }
                _status = 0;
                return "ok";
            }
            return $"链接错误代码：{iret}";
        }
    }
}
